package methodCallTreeGen;

import utils.Utils;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

import static utils.Utils.writeLineToDstFile;

/**
 * 重新组织Traces的结构
 */
public class ReformatTraces {
    /**
     * 给定一个Traces源文件，从中摘出 Add Set root,Add Class root,NewS,New和Put和PutA 操作
     * 并对这些Traces重新组织，使得Add Set root,Add Class root,NewS,New操作放在一个文件，Put和PutA 操作放在另一个文件
     * @param srcFilePath
     * @param dstFolderPath
     * @throws FileNotFoundException
     */
    public static void extractTracesAndReformat(String srcFilePath, String dstFolderPath) throws FileNotFoundException {
        // 输出Add Set root和Add Class root和NewS,New Traces的文件路径
        String beforeMainMethodNewObjTracesPath = dstFolderPath + "beforeMainNewObjTraces.txt";

        // 输出main函数开始前的Put和PutA Traces的文件路径
        String beforeMainMethodPutPutATracesPath = dstFolderPath + "beforeMainPutPutATraces.txt";
        Scanner scanner = new Scanner(new FileReader(srcFilePath));
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            // 将Add Set root和Add Class root和NewS以及New写入到beforeMainNewObjTraces.txt文件里面去
            if (Utils.isInputContainsPattern(line, "\\[gc,heap\\s+\\] (Add Set root|Add Class root|NewS|New)")) {
                // 将这行trace输出到文件中
                writeLineToDstFile(line, beforeMainMethodNewObjTracesPath);
                continue;
            }
            // 将Put和PutA traces输出到文件中
            if (Utils.isInputContainsPattern(line, "\\[gc,heap\\s+\\] (PutA|Put)")) {
                writeLineToDstFile(line, beforeMainMethodPutPutATracesPath);
            }
        }

        // 把新建对象和PutPutA traces两个文件合并在一起
        // 合并beforeMainNewObjTraces.txt和beforeMainPutPutATraces.txt两个文件
//        mergeFiles(beforeMainMethodPutPutATracesPath, beforeMainMethodNewObjTracesPath);
//        // 重命名beforeMainMethodNewObjTracesPath文件名
//        File oldFile = new File(beforeMainMethodNewObjTracesPath);
//        File newFile = new File(dstFolderPath + "beforeMainAndRemovedNodeUsefulTraces.txt");
//        oldFile.renameTo(newFile);
//        // 删除文件beforeMainMethodPutPutATracesPath
//        File file = new File(beforeMainMethodPutPutATracesPath);
//        if (file.exists()) {
//            file.delete();
//        }
    }
    public static void main(String[] args) throws FileNotFoundException {
        String srcFilePath = "src/test/resources/dslProgramGenForComplexMop/filteredTraces/14/beforeMainAndRemovedNodeTraces.txt";
        String dstFolderPath = "src/test/resources/dslProgramGenForComplexMop/filteredTraces/14/";
        extractTracesAndReformat(srcFilePath, dstFolderPath);
        // 对beforeMainUsefulTraces.txt进行处理，生成全局变量表，Main类静态初始化DSL代码块
//        processBeforeMainTraces(dstFolderPath + "beforeMainUsefulTraces.txt", dstFolderPath);
    }
}
